﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Coding4Fun.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System;

using ShoppingListEntities;
using ShoppingList.Model;
using System.Collections.ObjectModel;
using System.Linq;
using System.Collections.Generic;
using System.Windows;
using GalaSoft.MvvmLight.Messaging;
namespace ShoppingList.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class ProductsViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the ProductsViewModel class.
        /// </summary>
        /// 
        PhotoChooserTask PhotoChooser;
        CameraCaptureTask CameraChooser;
        private static bool swap;
        private ShoppingListDataContext dataContext;
        private Dictionary<string, List<Product>> DictionaryProducts;
        bool isNew;
        public ProductsViewModel()
        {
            dataContext = new ShoppingListDataContext(Helpers.DataBaseHelpers.Cnn);
            canUseButtons = true;
            canSaveCancelButtons = false;
            SetupCommands();
           PhotoChooser = new  PhotoChooserTask();
            CameraChooser = new CameraCaptureTask();
            PhotoChooser.Completed += new EventHandler<PhotoResult>(PhotoChooser_Completed);
            CameraChooser.Completed += new EventHandler<PhotoResult>(CameraChooser_Completed);

            SetupCollections();


            Messenger.Default.Register<Helpers.ShopListHelpers.ProductMenuCommands>(this,"PRODUCTCOMMANDS_TOKEN", (param) =>
            {
               

                ProductJumpListItem product = Products.Where(x => x.ProductId == param.ProductId).FirstOrDefault();
                Img = Helpers.DataBaseHelpers.LoadImage(product.CurrentProduct.ImageUri);
                UpdateProductCommand.Execute(product);
                
            });

         
            
        }

        #region Properties

        
        

        private ObservableCollection<ProductJumpListItem> _Products;
        public ObservableCollection<ProductJumpListItem> Products
        {
            get
            {
                return _Products;
            }

            set
            {
                _Products = value;
                RaisePropertyChanged("Products");
            }
        }

        private ProductJumpListItem _ProductItem;
        public ProductJumpListItem ProductItem
        {
            get { return _ProductItem; }

            set
            {
                _ProductItem = value;
                RaisePropertyChanged("ProductItem");
            }
        }
        private BitmapImage _Img;
        public BitmapImage Img
        {
            get
            {
                return _Img;
            }

            set
            {
                _Img = value;
                RaisePropertyChanged("Img");
            }
        }

        private bool _canUseButtons;
        public bool canUseButtons
        {
            get { return _canUseButtons; }
            set
            {
                _canUseButtons = value;
                RaisePropertyChanged("canUseButtons");
            }
        }

        private bool _canSaveCancelbuttons;
        public bool canSaveCancelButtons
        {
            get { return _canSaveCancelbuttons; }
            set
            {
                _canSaveCancelbuttons = value;
                RaisePropertyChanged("canSaveCancelButtons");
            }
        }

        private bool _ValidFields;
        public bool ValidFields
        {
            get { return _ValidFields; }
            set
            {
                _ValidFields = value;
                RaisePropertyChanged("ValidFields");
            }
        }
        #endregion

        #region Commands
        public RelayCommand ShowNewProductCommand { get; set; }
        public RelayCommand SelectImageCommand { get; set; }
        public RelayCommand SaveProductCommand { get; set; }
        public RelayCommand CancelCommand { get; set; }
        public RelayCommand DeleteProductCommand { get; set; }
        public RelayCommand<object> UpdateProductCommand { get; set; }
        public RelayCommand ShowGalleryCommand { get; set; }
        public RelayCommand ShowCameraCommand { get; set; }
        public RelayCommand DisableButtons { get; set; }
        public RelayCommand EnableButtons { get; set; }
        private void SetupCommands()
        {
            DisableButtons = new RelayCommand(() => 
            {
                canSaveCancelButtons = false;
                canUseButtons = false;
            });

            EnableButtons = new RelayCommand(() => 
            {
                canSaveCancelButtons = true;
                canUseButtons = false;
            });

            ShowGalleryCommand = new RelayCommand(() => 
            {

                PhotoChooser.Show();
            });

            ShowCameraCommand = new RelayCommand(() => 
            {

                CameraChooser.Show();
            });
            SaveProductCommand = new RelayCommand(() =>
            {

                if (isNew)
                {
                    if (ProductItem != null)
                    {
                        if (string.IsNullOrWhiteSpace(ProductItem.CurrentProduct.Name) )
                        {
                            ValidFields = false;
                            MessagePrompt message = new MessagePrompt {Title="El Nombre es requerido" };
                            message.Show();
                            return;
                        }

                        if (!Helpers.StringHelpers.NoNumberString(ProductItem.CurrentProduct.Name))
                        {
                            ValidFields = false;
                            MessagePrompt message = new MessagePrompt { Title = "No se permiten numeros en el campo nombre." };
                            message.Show();
                            return;
                        }
                        if (Img != null)
                        {
                            ProductItem.CurrentProduct.ImageUri = Helpers.DataBaseHelpers.SaveImage(Img);
                        }
                        ProductItem.CurrentProduct.DischargeDate = DateTime.Now.ToShortDateString();
                        ProductItem.CurrentProduct.ProductId = Guid.NewGuid();
                        ProductItem.CurrentProduct.Name = ProductItem.CurrentProduct.Name.Trim();
                        dataContext.Products.InsertOnSubmit(ProductItem.CurrentProduct);
                        Products.Add(ProductItem);
                        ValidFields = true;
                        
                    }
                }
                else
                {
                    if (ProductItem != null)
                    {
                        if (string.IsNullOrWhiteSpace(ProductItem.CurrentProduct.Name))
                        {
                            ValidFields = false;
                            MessagePrompt message = new MessagePrompt { Title = "El Nombre es requerido" };
                            message.Show();
                            return;
                        }

                        if (!Helpers.StringHelpers.NoNumberString(ProductItem.CurrentProduct.Name))
                        {
                            ValidFields = false;
                            MessagePrompt message = new MessagePrompt { Title = "No se permiten numeros en el campo nombre." };
                            message.Show();
                            return;
                        }
                        Helpers.DataBaseHelpers.DeleteImage(ProductItem.CurrentProduct.ImageUri);
                        ProductItem.CurrentProduct.DischargeDate = DateTime.Now.ToShortDateString();
                        ProductItem.CurrentProduct.ImageUri = Helpers.DataBaseHelpers.SaveImage(Img);

                        var item = dataContext.Products
                            .Where(x => x.ProductId == ProductItem.CurrentProduct.ProductId).SingleOrDefault();

                        item.Name = ProductItem.CurrentProduct.Name;
                        item.Note = ProductItem.CurrentProduct.Note;
                        item.ImageUri = ProductItem.CurrentProduct.ImageUri;
                        ValidFields = true;
                    }
                }
               
                canUseButtons = true;
                canSaveCancelButtons = false;
                
                dataContext.SubmitChanges();
                SetupCollections();

            });

            CancelCommand = new RelayCommand(() => 
            {
                canUseButtons = true;
                canSaveCancelButtons = false;
            
            });
            ShowNewProductCommand = new RelayCommand(() => 
            {
                canUseButtons = false;
                canSaveCancelButtons = true;
                isNew = true;
                ProductItem = new ProductJumpListItem();
                Img = null;
            });

            SelectImageCommand = new RelayCommand(() =>
            {
                
                BitmapImage img1 = new BitmapImage(new Uri("/Icons/appbar.folder.rest.png", UriKind.Relative));
                BitmapImage img2 = new BitmapImage(new Uri("/Icons/appbar.feature.camera.rest.png", UriKind.Relative));
                var messagePrompt = new MessagePrompt
                {
                    Title = "De donde quieres tomar la foto?",
                   
                };

                var button1 = new RoundButton { Content = "Galería" };
                button1.ImageSource = img1;
                button1.Click += (o, arg) =>
                {
                    PhotoChooser.Show();

                    messagePrompt.Hide();
                };

                var button2 = new RoundButton { Content = "Cámara" };
                button2.ImageSource = img2;
                button2.Click += (o, arg) => 
                { 
                   
                    
                    CameraChooser.Show();
                    messagePrompt.Hide();
                };

                messagePrompt.ActionPopUpButtons.Clear();
                messagePrompt.ActionPopUpButtons.Add(button1);
                messagePrompt.ActionPopUpButtons.Add(button2);

                messagePrompt.Completed += stringObject_Completed;

                messagePrompt.Show();


            });

            DeleteProductCommand = new RelayCommand(() =>
            {

                if (ProductItem != null)
                {
                    MessageBoxResult res = MessageBox.Show("Realmente deseas eliminar este Producto? se borrará de forma permanente.", "Advertencia", MessageBoxButton.OKCancel);
                    if (res == MessageBoxResult.OK)
                    {
                        Helpers.DataBaseHelpers.DeleteImage(this.ProductItem.CurrentProduct.ImageUri);
                        dataContext.Products.DeleteOnSubmit(ProductItem.CurrentProduct);
                        this.Products.Remove(ProductItem);
                        dataContext.SubmitChanges();
                    }
                }
            });

            UpdateProductCommand = new RelayCommand<object>((obj) =>
            {
                ProductJumpListItem product = obj as ProductJumpListItem;


                Img = Helpers.DataBaseHelpers.LoadImage(product.CurrentProduct.ImageUri);
                isNew = false;
                canUseButtons =false;
                canSaveCancelButtons = true;
                product.CurrentProduct.Name = product.CurrentProduct.Name.Trim();
                this.ProductItem = product;
                Messenger.Default.Send<string>("ShowNewProduct", "PRODUCTANIMATIONS_TOKEN");
            });
        }

        void stringObject_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
            string str = GetBaseResult(e.PopUpResult) + e.Result;
        }

        private string GetBaseResult(PopUpResult popUp)
        {
            var result = "meh?";

            if (popUp == PopUpResult.Ok)
                result = "OK!";
            else if (popUp == PopUpResult.Cancelled)
                result = "CANCELLED!";

            return result;
        }
        #endregion
        

        #region Methods

        private void SetupCollections()
        {
            Products = new ObservableCollection<ProductJumpListItem>();

            InitItems();


        }

        void CameraChooser_Completed(object sender, PhotoResult e)
        {
            if (e.ChosenPhoto != null)
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.ChosenPhoto);
                this.Img = image;
            }


        }

        void PhotoChooser_Completed(object sender, PhotoResult e)
        {
            if (e.ChosenPhoto != null)
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.ChosenPhoto);
                this.Img = image;
            }


        }


        protected virtual void InitItems()
        {
            Products = new ObservableCollection<ProductJumpListItem>();
            bool isHeader=false;
            //GroupingProducts();
            DictionaryProducts = Helpers.ShopListHelpers.getJumpListProducts();
            int count = 0;
            foreach (var item in DictionaryProducts)
            {
                count = 1;
                

                foreach (var subitem in item.Value)
                {
                    if (count == 1) { isHeader = true; }
                    if (isHeader) { Products.Add(new ProductJumpListItem(count, item.Key) { IsEnabled = true, IsHeader = true }); isHeader = false; }
                    count++;
                    ProductJumpListItem jump = new ProductJumpListItem(count, item.Key);
                    jump.CurrentProduct = subitem;
                    jump.ProductId = subitem.ProductId.ToString();
                    Products.Add(jump);

                }
                isHeader = true;
            }
        }

    


        private void GroupingProducts()
        {
            DictionaryProducts = new Dictionary<string, List<Product>>();
            var resultA = dataContext.Products.Where(x => x.Name[0] == 'A' || x.Name[0] == 'a');
            var resultB = dataContext.Products.Where(x => x.Name[0] == 'B' || x.Name[0] == 'b');
            var resultC = dataContext.Products.Where(x => x.Name[0] == 'C' || x.Name[0] == 'c');
            var resultD = dataContext.Products.Where(x => x.Name[0] == 'D' || x.Name[0] == 'd');
            var resultE = dataContext.Products.Where(x => x.Name[0] == 'E' || x.Name[0] == 'e');
            var resultF = dataContext.Products.Where(x => x.Name[0] == 'F' || x.Name[0] == 'f');
            var resultG = dataContext.Products.Where(x => x.Name[0] == 'G' || x.Name[0] == 'g');
            var resultH = dataContext.Products.Where(x => x.Name[0] == 'H' || x.Name[0] == 'h');
            var resultI = dataContext.Products.Where(x => x.Name[0] == 'I' || x.Name[0] == 'i');
            var resultJ = dataContext.Products.Where(x => x.Name[0] == 'J' || x.Name[0] == 'j');
            var resultK = dataContext.Products.Where(x => x.Name[0] == 'K' || x.Name[0] == 'k');
            var resultL = dataContext.Products.Where(x => x.Name[0] == 'L' || x.Name[0] == 'l');
            var resultM = dataContext.Products.Where(x => x.Name[0] == 'M' || x.Name[0] == 'm');
            var resultN = dataContext.Products.Where(x => x.Name[0] == 'N' || x.Name[0] == 'n');
            var resultO = dataContext.Products.Where(x => x.Name[0] == 'O' || x.Name[0] == 'o');
            var resultP = dataContext.Products.Where(x => x.Name[0] == 'P' || x.Name[0] == 'p');
            var resultQ = dataContext.Products.Where(x => x.Name[0] == 'Q' || x.Name[0] == 'q');
            var resultR = dataContext.Products.Where(x => x.Name[0] == 'R' || x.Name[0] == 'r');
            var resultS = dataContext.Products.Where(x => x.Name[0] == 'S' || x.Name[0] == 's');
            var resultT = dataContext.Products.Where(x => x.Name[0] == 'T' || x.Name[0] == 't');
            var resultU = dataContext.Products.Where(x => x.Name[0] == 'U' || x.Name[0] == 'u');
            var resultV = dataContext.Products.Where(x => x.Name[0] == 'V' || x.Name[0] == 'v');
            var resultW = dataContext.Products.Where(x => x.Name[0] == 'W' || x.Name[0] == 'w');
            var resultX = dataContext.Products.Where(x => x.Name[0] == 'X' || x.Name[0] == 'x');
            var resultY = dataContext.Products.Where(x => x.Name[0] == 'Y' || x.Name[0] == 'y');
            var resultZ = dataContext.Products.Where(x => x.Name[0] == 'Z' || x.Name[0] == 'z');
            DictionaryProducts.Add("a", resultA.ToList());
            DictionaryProducts.Add("b", resultB.ToList());
            DictionaryProducts.Add("c", resultC.ToList());
            DictionaryProducts.Add("d", resultD.ToList());
            DictionaryProducts.Add("e", resultE.ToList());
            DictionaryProducts.Add("f", resultF.ToList());
            DictionaryProducts.Add("g", resultG.ToList());
            DictionaryProducts.Add("h", resultH.ToList());
            DictionaryProducts.Add("i", resultI.ToList());
            DictionaryProducts.Add("j", resultJ.ToList());
            DictionaryProducts.Add("k", resultK.ToList());
            DictionaryProducts.Add("l", resultL.ToList());
            DictionaryProducts.Add("m", resultM.ToList());
            DictionaryProducts.Add("n", resultN.ToList());
            DictionaryProducts.Add("o", resultO.ToList());
            DictionaryProducts.Add("p", resultP.ToList());
            DictionaryProducts.Add("q", resultQ.ToList());
            DictionaryProducts.Add("r", resultR.ToList());
            DictionaryProducts.Add("s", resultS.ToList());
            DictionaryProducts.Add("t", resultT.ToList());
            DictionaryProducts.Add("u", resultU.ToList());
            DictionaryProducts.Add("v", resultV.ToList());
            DictionaryProducts.Add("w", resultW.ToList());
            DictionaryProducts.Add("x", resultX.ToList());
            DictionaryProducts.Add("y", resultY.ToList());
            DictionaryProducts.Add("z", resultZ.ToList());
        
        }

        
        #endregion
    }
}